package com.berchen.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * LockSupport就是阻塞唤醒线程的高级方式
 */
public class LockSupportDemo {

    static Object objectLock=new Object();

    /**
     * 使用wait阻塞 notify唤醒
     */
    public static void object(){

        new Thread(()->{
            synchronized (objectLock){
                System.out.println(Thread.currentThread().getName()+"\t ----- come in ");
                try {
                    objectLock.wait();// 睡眠 等待唤醒 --该线程阻塞在这里，该线程必须被唤醒才能回到运行状
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"\t 被唤醒");
            }
        },"A").start();
        new Thread(()->{
            synchronized (objectLock){
                objectLock.notify();
                System.out.println(Thread.currentThread().getName()+"\t ----- 唤醒动作");

            }
        },"B").start();

    }
    static Lock lock=new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void condition(){

        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"\t ----- come in ");
                condition.await();  // 睡眠 等待唤醒 --该线程阻塞在这里
                System.out.println(Thread.currentThread().getName()+"\t 被唤醒");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"A1").start();

        new Thread(()->{
            try {
                lock.lock();
                condition.signal(); // 唤醒睡眠的线程
                System.out.println(Thread.currentThread().getName()+"\t ----- 唤醒动作");
            } finally {
                lock.unlock();
            }
        },"B1").start();

    }

    public static void main(String[] args){

        object();
        condition();

    }
}
